﻿using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.IO;


/// <summary>
/// 支持多种列表方式：详细(GridView)、图标+文件名(DataList)、缩略图(DataList)，三种方式都可以编辑文件的标题。
/// 
/// </summary>
public partial class FileBrowser : System.Web.UI.Page
{
    //private string baseDirectory;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SetFileFilter();
            this.BaseDirectory = this.HtmlResourceDirectory ;
            BindFiles();
        }
    }

    protected string GetUrl(FileInfo fileInfo)
    {
        return Path.Combine(HtmlResourceUrl, fileInfo.Name);
    }

    protected void UploadButton_Click(object sender, EventArgs e)
    {
        string filename = Path.GetFileName(FileUpload1.FileName);
        this.FileUpload1.SaveAs(Path.Combine(BaseDirectory,filename));
        BindFiles();
    }

    private void SetFileFilter()
    {
        string fileType = Request.QueryString["FileType"];
        if (fileType != null)
        {
            fileType = fileType.ToLower();
        }
        // 下面的逻辑为根据配置文件（在web.config中，而不是fckconfig.js中）
        // 确定允许显示和上传的文件的扩展名
        switch (fileType)
        {
            case "image":
                break;
            case "flash":
                break;
            case "audio":
                break;
            case "vedio":
                break;
            default:
                break;
        }
    }

    public string BaseDirectory
    {
        get
        {
            return (string)ViewState["BaseDirecotory"];
        }
        set
        {
            if (Directory.Exists(value))
            {
                ViewState["BaseDirecotory"] = value;
            }
            else
            {
                throw new Exception("设定的目录不存在！");
            }
        }
    }

    public IList<FileInfo> GetFiles()
    {
        string[] files = Directory.GetFiles(BaseDirectory);
        IList<FileInfo> list = new List<FileInfo>();
        foreach (string file in files)
        {
            list.Add(new FileInfo(file));
        }
        return list;
    }

    public void BindFiles()
    {
        IList<FileInfo> list = GetFiles();
        this.FileList.DataSource = list;
        this.FileDetails.DataSource = list;
        this.FileIcon.DataSource = list;
        this.DataBind();
    }


    #region 定位资源的位置：URL地址和物理路径
    private const string DEFAULT_HTML_RESOURCE_URL = "/files/";

    private string htmlResourceUrl;
    private string htmlResourceDirectory;

    protected string HtmlResourceUrl
    {
        // 这部分的更改是优先使用查询字符串中指定的资源Url。
        // 该路径是基于Html的, 所以不要在路径中使用"~"等。
        get
        {
            if (htmlResourceUrl == null)
            {
                // First from QueryString
                htmlResourceUrl = Request.QueryString["HtmlResourceUrl"];

                // Try to get from the "Session".
                if (htmlResourceUrl == null || htmlResourceUrl.Length == 0)
                {

                    htmlResourceUrl = (string)Session["FCKeditor:HtmlResourceUrl"];

                    // Try to get from the Web.config file.
                    if (htmlResourceUrl == null || htmlResourceUrl.Length == 0)
                    {
                        htmlResourceUrl = System.Configuration.ConfigurationManager.AppSettings["FCKeditor:HtmlResourceUrl"];

                        // Otherwise use the default value.
                        if (htmlResourceUrl == null || htmlResourceUrl.Length == 0)
                        {
                            htmlResourceUrl = DEFAULT_HTML_RESOURCE_URL;
                        }

                    }
                }

                // Check that the user path ends with slash ("/")
                if (!htmlResourceUrl.EndsWith("/"))
                    htmlResourceUrl += "/";
            }
            return htmlResourceUrl;
        }
    }

    /// <summary>
    /// The absolution path (server side) of the user files directory. It 
    /// is based on the <see cref="FileWorkerBase.UserFilesPath"/>.
    /// </summary>
    protected string HtmlResourceDirectory
    {
        get
        {

            if (htmlResourceDirectory == null)
            {
                // First from QueryString
                htmlResourceDirectory = Request.QueryString["HtmlResourceDirectory"];

                // Try to get from the "Session".
                if (htmlResourceDirectory == null || htmlResourceDirectory.Length == 0)
                {

                    htmlResourceDirectory = (string)Session["FCKeditor:HtmlResourceDirectory"];

                    // Try to get from the Web.config file.
                    if (htmlResourceDirectory == null || htmlResourceDirectory.Length == 0)
                    {
                        htmlResourceDirectory = System.Configuration.ConfigurationManager.AppSettings["FCKeditor:HtmlResourceDirectory"];

                        // Otherwise use the default value.
                        if (htmlResourceDirectory == null || htmlResourceDirectory.Length == 0)
                        {
                            try
                            {
                                htmlResourceDirectory = Server.MapPath(this.HtmlResourceUrl);
                            }
                            // 忽略错误：在2005中使用文件系统建站时不支持以/开始的路径的映射。
                            catch { }
                        }

                    }
                }
            }
            return htmlResourceDirectory;
        }
    }
    #endregion

}

